package de.lns.render;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;

import org.lwjgl.opengl.GL11;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.HashMap;

import de.lns.tick.UpdateThread;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;


public class TextureLoader {
	
	/**Make the constructor invisible.
	 * Since this is a static-access class,
	 * it shouldn't be instantiated.
	 */
	private TextureLoader(){};
	
	private static final String TEXTURE_PATH = "data/textures/";
	
	//The map of all loaded images.
	private static HashMap<String, Integer> lookupTable = new HashMap<String, Integer>();
	
	
	public static int loadTexture(String texturepath) {
		/*
		 * If the texture in question is already loaded
		 * to the Graphics Adapter's memory,
		 * return its pointer.
		 */
		if(lookupTable.containsKey(texturepath)){
			return lookupTable.get(texturepath);
		}
		
		/*
		 * If the texture is not loaded,
		 * read it from its file.
		 */
		int texturePointer = 0;
		try {
			InputStream in = new FileInputStream(TEXTURE_PATH + texturepath);
		   PNGDecoder decoder = new PNGDecoder(in);

		   ByteBuffer buf = ByteBuffer.allocateDirect(4*decoder.getWidth()*decoder.getHeight());
		   decoder.decode(buf, decoder.getWidth()*4, Format.RGBA);
		   buf.flip();
		   
		   //Tell OpenGL to reserve memory for the Texture
		   texturePointer = glGenTextures();
		   glBindTexture(GL_TEXTURE_2D, texturePointer);
		   
		   //Put the loaded texture into graphics memory
		   	//(target, level, internalformat, width, height, border, format, type, pixels)
		   glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 
				   decoder.getWidth(), decoder.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
		   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
		   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
		   glBindTexture(GL_TEXTURE_2D, 0);
		   
		   in.close();
		} catch (FileNotFoundException e) {
			UpdateThread.kill("Invalid Texture path!", e);
		} catch (IOException e){System.out.println("IOExeption");}
		
		lookupTable.put(texturepath, texturePointer);
		//System.out.print("Loaded tex: ");
		//System.out.println(texturePointer);
		return texturePointer;
		
	}


	public static void dispose() {
		// TODO Auto-generated method stub
		
	}
	
	
}
